package cn.blunce.utils.XmlParse;

import android.util.Xml;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class PullParsePerson {

    public static List<Person> getPersons(InputStream in) throws Exception {
        Person person = null;
        List<Person> persons = null;

        XmlPullParser pullParser = Xml.newPullParser();
        pullParser.setInput(in, "UTF-8");
        int event = pullParser.getEventType();
        while (event != XmlPullParser.END_DOCUMENT) {
            switch (event) {
                case XmlPullParser.START_DOCUMENT:
                    persons = new ArrayList<Person>();
                    break;
                case XmlPullParser.START_TAG:
                    if ("person".equals(pullParser.getName())) {
                        Integer id = Integer.valueOf(pullParser
                                .getAttributeValue(0));
                        person = new Person();
                        person.setId(id);
                    }
                    if (person != null) {
                        if ("name".equals(pullParser.getName())) {
                            person.setName(pullParser.nextText());
                        }
                        if ("age".equals(pullParser.getName())) {
                            person.setAge(new Short(pullParser.nextText()));
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("person".equals(pullParser.getName())) {
                        persons.add(person);
                        person = null;
                    }
                default:
                    break;
            }
            event = pullParser.next();
        }

        return persons;
    }

    public static void PullParsePersonToOutStream(List<Person> list,
                                                  OutputStream out) throws Exception {
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(out, "UTF-8");
        serializer.startDocument("UTF-8", true);
        serializer.startTag(null, "persons");
        for (Person person : list) {
            serializer.startTag(null, "person");
            serializer.attribute(null, "id", person.getId().toString());
            serializer.startTag(null, "name");
            serializer.text(person.getName());
            serializer.endTag(null, "name");
            serializer.startTag(null, "age");
            serializer.text(String.valueOf(person.getAge()));
            serializer.endTag(null, "age");
            serializer.endTag(null, "person");
        }
        serializer.endTag(null, "persons");
        serializer.endDocument();
        out.flush();
        out.close();
    }
}
